package com.lmf.cloud.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmf.cloud.controller.feign.SeataAccountFeign;
import com.lmf.cloud.controller.feign.SeataStorageFeign;
import com.lmf.cloud.entity.TOrder;
import com.lmf.cloud.mapper.TOrderMapper;
import com.lmf.cloud.resp.ResultData;
import com.lmf.cloud.service.TOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuMingFu
 * @since 2024-08-01
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Resource
    private TOrderMapper tOrderMapper;
    @Resource
    private SeataAccountFeign seataAccountFeign;
    @Resource
    private SeataStorageFeign seataStorageFeign;
    private SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();

    /**
     * 获取所有订单信息
     *
     * @return
     * @author LiuMingFu
     * @date 2024/8/1
     */
    @Override
    public ResultData<List<TOrder>> getAllOrder(Long userId) {
        if (userId == null) {
            return ResultData.fail("500", "userId不能为空");
        }
        List<TOrder> list = this.lambdaQuery().eq(TOrder::getUserId, userId).list();
        return ResultData.success(list);
    }


    /**
     * 创建订单
     *
     * @param tOrder@return
     * @author LiuMingFu
     * @date 2024/8/1
     */
    @GlobalTransactional(name = "tx-group", rollbackFor = Exception.class)
    @Override
    public ResultData<Boolean> createOrder(TOrder tOrder) {
        if (tOrder == null) {
            return ResultData.fail("500", "订单不能为空");
        }
        //插入一条订单，状态为创建中
        tOrder.setId(snowflakeGenerator.next());
        tOrder.setStatus(0);
        tOrderMapper.insert(tOrder);
        //调用远程服务-扣减账户余额
        seataAccountFeign.decreaseAccount(tOrder.getUserId(), Integer.valueOf(tOrder.getMoney().toString()));
//            Thread.sleep(30000);
        int i = 1 / 0;
        //调用远程服务-扣减库存
        seataStorageFeign.decreaseStorage(tOrder.getProductId(), tOrder.getCount());
        //更新订单状态为已完结
        tOrder.setStatus(1);
        tOrderMapper.updateById(tOrder);

        return ResultData.success(true);
    }
}
